HackerRank The Power Sum
提出
code: python
import math
import os
import random
import re
import sys
#
# Complete the 'powerSum' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER X
# 2. INTEGER N
#
def powerSum(X, N):
# Write your code here
nums = []
i = 1
while (True):
res = pow(i, N)
if (res > X):
break
else:
nums.append(res)
i += 1
# for i in nums:
# for j in range(X+1):
# print(dp)
if __name__ == '__main__':
X = int(input().strip())
N = int(input().strip())
result = powerSum(X, N)
fptr.write(str(result) + '\n')
fptr.close()
解答
code: python
import math
import os
import random
import re
import sys
#
# Complete the 'powerSum' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER X
# 2. INTEGER N
#
def powerSum(X, N):
# Write your code here
def helper(total, power, num):
val = total - num**power
# base condition
if val == 0:
return 1
if val < 0:
return 0
# recursive calls to compute all combionations
return helper(val, power, num+1) + helper(total, power, num+1)
return helper(X, N, 1)
if __name__ == '__main__':
X = int(input().strip())
N = int(input().strip())
result = powerSum(X, N)
fptr.write(str(result) + '\n')
fptr.close()
メモ
https://www.youtube.com/watch?v=AIw5ljcTuyg
使ったか、使ってないかで分岐
https://scrapbox.io/files/61d3954ff7b1bc0021cc89dd.png
提出
code: python
import math
import os
import random
import re
import sys
import itertools
#
# Complete the 'powerSum' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER X res
# 2. INTEGER N pow
#
def powerSum(X, N):
# Write your code here
# pow(2, 1000)
# max = pow(32, 2)
# print(pow(2, 32)) 4294967296
for p in list(itertools.product(0, 1, repeat=10)): print(p)
# pick up 1 and sum
if __name__ == '__main__':
X = int(input().strip())
N = int(input().strip())
result = powerSum(X, N)
fptr.write(str(result) + '\n')
fptr.close()